package cc.comac.mom.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cc.comac.mom.api.EquipRepairRepositoryRepairDocService;
import cc.comac.mom.api.QualityAttachmentService;
import cc.comac.mom.bean.EquipRepairRepository;
import cc.comac.mom.bean.EquipRepairRepositoryRepairDoc;
import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.config.OSSService;
import cc.comac.mom.datahandlers.entity.EquipRepairRepositoryDataHandler;
import cc.comac.mom.datahandlers.entity.EquipRepairRepositoryRepairDocDataHandler;
import cc.comac.mom.entity.EquipRepairRepositoryEntity;
import cc.comac.mom.entity.EquipRepairRepositoryRepairDocEntity;
import cc.comac.mom.entity.QualityAttachmentEntity;
import cc.comac.mom.util.ResultBean;

@Service
@RestController
public class EquipRepairRepositoryRepairDocServiceImpl implements EquipRepairRepositoryRepairDocService{
	@Autowired
	private EquipRepairRepositoryRepairDocDataHandler EquipRepairRepositoryRepairDocDataHandler;
	
	@Value("${upload.tempDir}")
	private String rootPath;
	
	@Autowired
	private EquipRepairRepositoryDataHandler equipRepairRepositoryDataHandler;
	@Autowired
	private QualityAttachmentService qualityAttachmentService;
	@Autowired
	private OSSService oSSService;
	@Override
	public ResultBean save(@RequestBody EquipRepairRepositoryRepairDoc obj) {
		String documentName = obj.getInnerData().getDocumentName();
		// 获取文件路径名
		String path = rootPath + "\\" + documentName;
		File file = new File(path);
		// 保存文档信息
		DecimalFormat df = new DecimalFormat("0.00");
		String formatMB = df.format((float) file.length() / 1048576);
		obj.getInnerData().setDocumentSize(formatMB+"MB");
		obj.getInnerData().setDoucumentRealPath(path);
		return EquipRepairRepositoryRepairDocDataHandler.save(obj);
	}
	
	@Override
	public ResultBean delete(@RequestBody EquipRepairRepositoryRepairDoc obj) {
		return EquipRepairRepositoryRepairDocDataHandler.delete(obj);
	}
	
	@Override
	public ResultBean update(@RequestBody EquipRepairRepositoryRepairDoc obj) {
		return EquipRepairRepositoryRepairDocDataHandler.update(obj);
	}
	
	@Override
	public ResultBean save(@RequestBody List<EquipRepairRepositoryRepairDoc> list) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("equip_category_id", list.get(0).getEquipCategoryId());
		map.put("fault_cause_id", list.get(0).getFaultCauseId());
		map.put("row_status", 1);
		Collection<EquipRepairRepositoryEntity> listByMap = equipRepairRepositoryDataHandler.listByMap(map);
		if (listByMap != null && listByMap.size() > 0) {
			// 主表信息已存在
			long equipRepairRepositoryId = 0;
			for (EquipRepairRepositoryEntity item : listByMap) {
				equipRepairRepositoryId = item.getId();
			}
			for (EquipRepairRepositoryRepairDoc item : list) {
				
				QualityAttachmentEntity byAttachmentId = qualityAttachmentService.getByAttachmentId(item.getInnerData().getAttachmentId());
				
				
				item.getInnerData().setEquipRepairRepositoryId(equipRepairRepositoryId);
				// 获取文件路径名
				String path = byAttachmentId.getFilePath();
				URL url = oSSService.getUrl(path);
				
				// 保存文档信息
				item.getInnerData().setDocumentSize(byAttachmentId.getFileSize());
				item.getInnerData().setDoucumentRealPath(byAttachmentId.getFilePath());
				item.getInnerData().setOssDoucumentPath(url.toString());
			} 

		}else {
			// 主表信息不存在
			EquipRepairRepository equipRepairRepository = new EquipRepairRepository();
			EquipRepairRepositoryEntity equipRepairRepositoryEntity = new EquipRepairRepositoryEntity();
			equipRepairRepositoryEntity.setEquipCategoryId(list.get(0).getEquipCategoryId());
			equipRepairRepositoryEntity.setFaultCauseId(list.get(0).getFaultCauseId());
			equipRepairRepository.setInnerData(equipRepairRepositoryEntity);
			ResultBean resultBean2 = equipRepairRepositoryDataHandler.save(equipRepairRepository);
			if (!resultBean2.success) {
				return resultBean2;
			}
			long equipRepairRepositoryId = Long.valueOf(resultBean2.getMessage());
			for (EquipRepairRepositoryRepairDoc item : list) {
				QualityAttachmentEntity byAttachmentId = qualityAttachmentService.getByAttachmentId(item.getInnerData().getAttachmentId());
				item.getInnerData().setEquipRepairRepositoryId(equipRepairRepositoryId);
				// 获取文件路径名
				String path = byAttachmentId.getFilePath();
				URL url = oSSService.getUrl(path);
				
				// 保存文档信息
				item.getInnerData().setDocumentSize(byAttachmentId.getFileSize());
				item.getInnerData().setDoucumentRealPath(byAttachmentId.getFilePath());
				item.getInnerData().setOssDoucumentPath(url.toString());
			}
		}
		return EquipRepairRepositoryRepairDocDataHandler.save(list);
	}
	
	@Override
	public ResultBean update(@RequestBody List<EquipRepairRepositoryRepairDoc> list) {
		return EquipRepairRepositoryRepairDocDataHandler.update(list);
	}
	
	@Override
	public ResultBean delete(@RequestBody List<EquipRepairRepositoryRepairDoc> list) {
		return EquipRepairRepositoryRepairDocDataHandler.delete(list);
	}
	@Override
	public EquipRepairRepositoryRepairDoc getById(@RequestParam long id) {
		ResultBean resultBean = new ResultBean(true);
		 EquipRepairRepositoryRepairDoc byId = EquipRepairRepositoryRepairDocDataHandler.getById(id);
		 return byId;
	}

	@Override
	public ResultBean previewPdf(HttpServletRequest request, HttpServletResponse response,@RequestParam long repairDocId) {
		ResultBean resultBean = new ResultBean(true, ' ');
		if (repairDocId == 0L) {
			resultBean.setSuccess(false);
			resultBean.setMessage("当前未选中数据");
			return resultBean;
		}
		EquipRepairRepositoryRepairDoc byId = EquipRepairRepositoryRepairDocDataHandler.getById(repairDocId);
		File file = new File(byId.getInnerData().getDoucumentRealPath());
		if (file.exists()) {
			byte[] data = null;
			try {
				FileInputStream input = new FileInputStream(file);
				data = new byte[input.available()];
				input.read(data);
				response.getOutputStream().write(data);
				input.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			throw new RuntimeException("无法找到当前文件路径");
		}
		return resultBean;
	}

	@Override
	public ResultBean download(@RequestParam Long documentId, HttpServletResponse response) {
		ResultBean resultBean = new ResultBean(true);
		EquipRepairRepositoryRepairDocEntity repositoryRepairDocEntity = EquipRepairRepositoryRepairDocDataHandler.getById(documentId);
		// 判断是否选中某条数据
		if (repositoryRepairDocEntity == null) {
			resultBean.setSuccess(false);
			resultBean.setMessage("数据不存在");
			return resultBean;
		}
		// 获取文件上传路径和真实文件名
		String path = repositoryRepairDocEntity.getDoucumentRealPath();
		String realName = repositoryRepairDocEntity.getDocumentName();
		try {
			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 取得文件的后缀名。
			String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(realName.getBytes("UTF-8"), "ISO8859-1"));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return resultBean;
	}

	@Override
	public ResultBean selectByCondition(@RequestBody EquipRepairRepositoryRepairDoc obj) {
		ResultBean resultBean = new ResultBean(true);
		ResultDev resultDev = EquipRepairRepositoryRepairDocDataHandler.selectByCondition(obj);
		resultBean.setObject(resultDev);
		return resultBean;
	}

}
